package com.ztesoft.web.taskscheduling;

import java.util.List;

import javax.annotation.Resource;

import com.ztesoft.core.cache.EhCacheService;
import com.ztesoft.core.spring.context.SpringApplicationContextHolder;
import com.ztesoft.core.threadpool.GeneralThreadPool;
import com.ztesoft.core.threadpool.ThreadPoolFactory;
import com.ztesoft.framework.exception.BaseAppException;
import com.ztesoft.framework.log.ZTEsoftLogManager;
import com.ztesoft.framework.util.Utils;
import com.ztesoft.web.baseconfig.db.dao.DmDataStateDao;
import com.ztesoft.web.baseconfig.service.IDmDataStateService;
import com.ztesoft.web.common.Configuration;
import com.ztesoft.web.common.DMSConstant;
import com.ztesoft.web.common.db.dao.SysParamDao;
import com.ztesoft.web.common.vo.TaskNotify;
import com.ztesoft.web.taskgenerator.db.arg.DmTaskArg;
import com.ztesoft.web.taskgenerator.db.dao.DmTaskDao;
import com.ztesoft.web.taskgenerator.db.po.DmTaskPO;
import com.ztesoft.web.taskscheduling.service.SystemStartInitInfoService;
import com.ztesoft.web.taskscheduling.service.TaskExecchildThreadService;


public class TaskManage extends Thread {

	/**
	 * 日志
	 */
	private final static ZTEsoftLogManager LOGGER = ZTEsoftLogManager
			.getLogger(TaskManage.class);
	private int sleepTime;
	private int maxTaskCount;
	private int count;
	private GeneralThreadPool threadPool = null;
//	private List<Future<DmTaskPO>> futureList;
//	private final static Map<Integer, DmTaskPO> taskInstList = new HashMap<Integer, DmTaskPO>();
	
	private SysParamDao sysParamDao;
	
	private DmTaskDao dmTaskDao;
	
	private SystemStartInitInfoService systemStartInitInfo;
	
	private TaskExecchildThreadService taskExecchildThreadService;
	
	private EhCacheService dmsCacheService;
	
	private List<DmTaskPO> dmTaskPOLst;
	
	public void init() {
		if (!Configuration.getBoolean("TaskManage", false))
			return;
		taskExecchildThreadService = SpringApplicationContextHolder.getBean(TaskExecchildThreadService.class);
		sysParamDao = SpringApplicationContextHolder.getBean(SysParamDao.class);
		dmTaskDao = SpringApplicationContextHolder.getBean(DmTaskDao.class);
		systemStartInitInfo = SpringApplicationContextHolder.getBean(SystemStartInitInfoService.class);
		dmsCacheService = (EhCacheService) SpringApplicationContextHolder.getBean("frameworkEhCacheService");
		sleepTime = (int)(Configuration.getDouble("sleepTime", 1) * 1000 * 60);
		systemStartInitInfo.taskManage();
		iniData();
		this.start();
	}

	public void iniData() {
		// 应用启动时获取系统配置相关参数：
		// 1.1营业开始时间,1.2营业结束时间1.3最大可执行任务数
		String maxTaskNum = sysParamDao.selectByParamName("MAX_TASK_NUM").getParamValue();
		//执行中任务数
		DmTaskArg arg = new DmTaskArg();
		arg.createCriteria().andStateEqualTo("00R");
		count = dmTaskDao.countByArg(arg).get(0);
		maxTaskCount = Integer.parseInt(maxTaskNum);
//		futureList = new ArrayList<Future<DmTaskPO>>(maxTaskCount-count);
		//应用启动后，读取DM_DATA_STATE的表，加载到内存中供任务调度程序进行判断使用

	}
	
	@Override
    public void run() {
	    while(true){
			iniData();
//            if (count == maxTaskCount) {
//                try {
//                    Thread.sleep(sleepTime);
//                    continue;
//                }catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }else{
            	try {
					threadPool = ThreadPoolFactory.createGeneralBoundedThreadPool("taskSchedule", //
							maxTaskCount-count,maxTaskCount-count);
				} catch (BaseAppException e1) {
					e1.printStackTrace();
				}
            	if(taskExecchildThreadService.isInBusTime()){//营业时间
            		dmTaskPOLst = dmTaskDao.getBusDmTaskPO();
    			}else{
    				dmTaskPOLst = dmTaskDao.getNotBusDmTaskPO();
    			}
            	if(!Utils.isEmpty(dmTaskPOLst)){
//            		LOGGER.info("获取待执行任务数:{0}",dmTaskPOLst.size());
            		TaskNotify notify = null;
            		for (DmTaskPO dmTaskPO : dmTaskPOLst) {
            			//Integer state = DMSConstant.dataRestore.get(dmTaskPO.getDmPlanId());
            			Integer state = (Integer) dmsCacheService.get("dmsCache", "dataRecovery_"+dmTaskPO.getDmPlanId());
						if (Utils.notEmpty(state)) {
							if (state == 1 || state == 2 || state == 4) {
								LOGGER.debug("任务调度模块中的数据恢复状态为" + state);
								continue;
							}
							// 判断同一个计划下，多个策略组，多个任务，的其他任务是否也已经数据恢复完成
							boolean isOK = true;
							if (state == 3) {
								List<DmTaskPO> dtPOList = dmTaskDao.selectBydmPlanId(dmTaskPO.getDmPlanId());
								for (DmTaskPO dtPO : dtPOList) {
									if ("00S".equals(dtPO.getState())) {// 还有没确认数据恢复完成的任务，不能启动下一周期的任务
										isOK = false;
										break;
									}
								}
							}
							if (!isOK) {
								continue;
							}
						}
            			notify = DMSConstant.taskInstList.get(dmTaskPO.getDmTaskId());
            			if (notify == null) {				
            				notify = new TaskNotify();
            				notify.setStatus("00T");
            				DMSConstant.taskInstList.put(dmTaskPO.getDmTaskId(),notify);
            			}
            			notify = DMSConstant.taskInstList.get(dmTaskPO.getDmTaskId());
            			if("02P".equals(notify.getStatus())){
            				continue;
            			}
//            			}else{
//            				if(dmTaskPO.getSourceType() == DMSConstant.SOURCE_TYPE_FILE){//文件类型，预留接口
//            					
//            				}else if (dmTaskPO.getSourceType() == DMSConstant.SOURCE_TYPE_TABLE){
            					//查询目标表对应数据库主机的内存、CPU、表空间使用情况
            					//创建任务执行子线程
//            					Future<DmTaskPO> future = 
            					LOGGER.info("|调度任务执行线程|TaskID={0}",dmTaskPO.getDmTaskId());
            					threadPool.submit(new TaskExecChildThread(dmTaskPO.getDmTaskId()));
//            					futureList.add(future);
//            				}
//            			}
            		}
//            		for (Future<DmTaskPO> future : futureList) {
//            			try {
//            				if ("sucess".equals(future.get().getScheduleResult())) {
//            					//LOGGER.info("\r\n|调度成功任务名称|"+future.get().getName());
////            					future.get().setState("00A");
////            					dmTaskDao.updateByPrimaryKey(future.get());
//            				} else if ("fail".equals(future.get().getScheduleResult())){
//            					//LOGGER.error("\r\n|调度失败任务名称|"+future.get().getName());
////            					future.get().setState("00F");
////            					dmTaskDao.updateByPrimaryKeySelective(future.get());//
//            				}
//            			} catch (InterruptedException e) {
//            				e.printStackTrace();
//            			} catch (ExecutionException e) {
//            				e.printStackTrace();
//            			}
//            		}
//            		try {
//            			threadPool.shutDown();
//            			Thread.sleep(sleepTime);
//            		} catch (InterruptedException e) {
//            			e.printStackTrace();
//            		}
//            	}else{
//            		try {
//            			threadPool.shutDown();
//						Thread.sleep(sleepTime);
//					} catch (InterruptedException e) {
//						e.printStackTrace();
//					}
//            	}

            }
            try {
                Thread.sleep(sleepTime);//
            }catch (InterruptedException e) {
                e.printStackTrace();
            }
	    }
	    
	}	

}